package GDoc::Job::Fetch::US::Exec::CFTC::TMFM;

use Moose;

use WWW::Mechanize;
use GDoc::Job;
use File::Temp;


extends 'GDoc::Job::Fetch';

my %MONTHS = ( January   =>  1, February =>  2, March    =>  3, April    =>  4,
               May       =>  5, June     =>  6, July     =>  7, August   =>  8,
               September =>  9, October  => 10, November => 11, December => 12 
             );


sub setup {
    my $self = shift;
    $self->_baseurl( 'http://www.cftc.gov/OCE/WEB/previous_reports.htm' );
    $self->_basedir( 'http://www.cftc.gov/OCE/WEB/' );
}

sub run { 
    my $self = shift;
   
    if ( $self->data->{link} ) { 
        $self->_fetch_pdf;
    } else { 
        $self->logger->info( "fetching base " . $self->_baseurl );
        my $mech = $self->_mech;
        $mech->get( $self->_baseurl );
        my @links = $mech->find_all_links( url_regex => qr{OCE_COT_Report_\w+_\d{4}\.pdf} );

        foreach my $link( @links ) { 
            my $title = $link->text;
            $title =~ m{(?<month>\w+)\s(?<year>\d{4})};
            my ( $month, $year ) = @+{ 'month', 'year' };

            my $job = GDoc::Job->new( class => 'Fetch::US::Exec::CFTC::TMFM',
                                      queue => $self->fetch_queue,
                                      data  => { link   => $link->url,
                                                 desc   => $title,
                                                 month  => $MONTHS{$month},
                                                 year   => $year
                                               }
                                    );
            $job->submit;
        }
    }
}

sub _fetch_pdf { 
    my $self = shift;
    my %data = %{ $self->data };

    my $ident = sprintf( 'CFTC-TMFM-%04d-%02d', $data{year}, $data{month} );
    my $filename = $ident . '.pdf';
    my $key = 'us/exec/cftc/' . $filename;

    $self->logger->info( "Storing $data{link} --> $key" );

    my $mech = $self->_mech;
    my $tmpf = File::Temp->new;
    $mech->get( $self->_basedir . $data{link}, ':content_file' => $tmpf->filename );

    $self->store_pdf( key      => $key,
                      datafile => $tmpf,
                      filename => $filename,
                      meta     => { description   => $data{desc},
                                    identifier    => $ident,
                                  }
                    );

}


1;
